package com.yhp.service.impl;

import com.sun.prism.impl.BaseContext;
import com.yhp.bo.OrderItemBO;
import com.yhp.enums.OrderStatusEnum;
import com.yhp.enums.YesOrNo;
import com.yhp.mapper.ItemsMapperCustom;
import com.yhp.mapper.OrderItemsMapper;
import com.yhp.mapper.OrderStatusMapper;
import com.yhp.mapper.OrdersMapper;
import com.yhp.pojo.*;
import com.yhp.service.AddressService;
import com.yhp.service.ItemService;
import com.yhp.service.OrderService;
import com.yhp.utils.DateUtil;
import com.yhp.vo.MerchantOrdersVO;
import com.yhp.vo.OrderVO;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper orderMapper;

    @Autowired
    private Sid sid;
    @Autowired
    private AddressService addressService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderItemsMapper orderItemsMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;

    //注意:一个订单有多个商品信息(一对多)，一个订单有一个订单状态(一对一)
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public OrderVO createOrder(OrderItemBO orderItemBO) {
        String userId = orderItemBO.getUserId();
        String addressId = orderItemBO.getAddressId();
        //步骤1.创建订单POJO对象
        Orders orders = new Orders();
        String orderId = sid.nextShort();
        orders.setId(orderId);
        orders.setUserId(userId);
        //调取其他接口方法获取收货人信息
        UserAddress userAddress = addressService.queryById(userId, addressId);
        orders.setReceiverName(userAddress.getReceiver());
        orders.setReceiverAddress(userAddress.getProvince()+" "+userAddress.getCity()
                +" "+userAddress.getDistrict()+" "+userAddress.getDetail());
        orders.setReceiverMobile(userAddress.getMobile());
        //   orders.setTotalAmount(); 设置总价格
        // orders.setRealPayAmount();实际支付金额
        int youfei=0;
        orders.setPostAmount(youfei);//设置邮费,这里设置为0,表示免邮费
        orders.setPayMethod(orderItemBO.getPayMethod());
        orders.setLeftMsg(orderItemBO.getLeftMsg());
        orders.setIsComment(YesOrNo.NO.type);//是否评论
        orders.setIsDelete(YesOrNo.NO.type);//是否进行逻辑删除
        orders.setCreatedTime(new Date());
        orders.setUpdatedTime(new Date());
        //步骤2.循环根据itemSpecIds(商品规格id) 保存订单商品信息表
        String[] specids = orderItemBO.getItemSpecIds().split(",");
        Integer totalAmont=0;//商品原价累计
        Integer realPayAmont=0;//优惠后的实际支付价格累计
        int buyCount=1;//单价*购物车数量，但是购物车数量并未传进来，这里需要从后台获取，即从redis中获取，现在假定为1
        for (String specid : specids) {
            //TODO 整合redis后,购买数量动态获取 buyCount





            //步骤2.1 根据规格id，查询具体规格的商品信息
            ItemsSpec itemsSpec = itemService.queryByItemSpecId(specid);
            totalAmont+=itemsSpec.getPriceNormal()*buyCount;
            realPayAmont+=itemsSpec.getPriceDiscount()*buyCount;
            //步骤2.2 根据商品id，获得商品信息及图片
            String itemId = itemsSpec.getItemId();
            Items items = itemService.queryItemById(itemId);
            ItemsImg itemsImg = itemService.queryItemMainImgById(itemId);
            //步骤2.3 循环保存子订单数据到数据库
            OrderItems orderItems = new OrderItems();
            orderItems.setId(sid.nextShort());
            orderItems.setOrderId(orderId);
            orderItems.setItemId(itemId);
            orderItems.setItemName(items.getItemName());
            orderItems.setItemImg(itemsImg.getUrl());
            orderItems.setBuyCounts(buyCount);
            orderItems.setItemSpecId(specid);
            orderItems.setItemSpecName(itemsSpec.getName());
            orderItems.setPrice(itemsSpec.getPriceDiscount());
            orderItemsMapper.insert(orderItems);
            //步骤2.4 扣除库存量
            itemService.updateStock(specid,buyCount);
        }
          orders.setTotalAmount(totalAmont); //设置总价格
          orders.setRealPayAmount(realPayAmont);//实际支付金额
          orderMapper.insert(orders);
          //步骤3.保存订单状态表
         //等待付款的订单状态
            OrderStatus orderStatus = new OrderStatus();
            orderStatus.setOrderId(orderId);
            orderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
            orderStatus.setCreatedTime(new Date());
            orderStatusMapper.insert(orderStatus);

          //步骤4:构建商户订单，用于传给支付中心
        MerchantOrdersVO merchantOrdersVO = new MerchantOrdersVO();
        merchantOrdersVO.setMerchantOrderId(orderId);
        merchantOrdersVO.setMerchantUserId(userId);
        merchantOrdersVO.setAmount(realPayAmont+youfei);
        merchantOrdersVO.setPayMethod(orderItemBO.getPayMethod());
        //步骤5: 构建自定义VO
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(orderId);
        orderVO.setMerchantOrdersVO(merchantOrdersVO);
        return orderVO;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateOrderStatus(String orderId, Integer orderStatus) {
        OrderStatus os = new OrderStatus();
        os.setOrderId(orderId);
        os.setOrderStatus(orderStatus);
        os.setPayTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(os);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderStatus getOrderStatus(String orderId) {
        return orderStatusMapper.selectByPrimaryKey(orderId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void closeOrder() {
        //查询所有未支付的订单，判断时间是否超过1天，超时则关闭交易订单
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> list = orderStatusMapper.select(orderStatus);
        for (OrderStatus status : list) {
            //获得订单创建时间
            Date createdTime = status.getCreatedTime();
            //和当前时间进行比较
            int days = DateUtil.daysBetween(createdTime, new Date());
            if(days>=1){
                changeStatus(status.getOrderId());
            }
        }
    }
    //修改订单状态为关闭状态
    @Transactional(propagation = Propagation.REQUIRED)
    void changeStatus(String orderId){
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setOrderStatus(OrderStatusEnum.CLOSE.type);
        orderStatus.setCloseTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(orderStatus);
    }


}
